<?php
/**
 * 文章管理
 */

namespace backend\modules\information\controllers;


use backend\component\BackendBaseController;
use backend\component\ResultFormat;
use backend\service\ArticleService;
use backend\service\TagService;
use common\models\info\Article;
use common\models\info\Tags;
use yii\helpers\ArrayHelper;

class ArticleController extends BackendBaseController
{
    public function actions()
    {
        return ArrayHelper::merge(parent::actions(),[
            "delete" =>[
                'class' => "backend\actions\DeleteAction",
                'modelName'=> Article::className(),
                'is_physics' => false
            ],
        ]);
    }

    public function actionList() {
        if (\Yii::$app->request->getIsAjax()) {
            $post = \Yii::$app->request->post();
            $post['is_think'] = \Yii::$app->request->get("think",0);
            return ArticleService::articleList($post);
        }
        $model = new Article();
        return $this->render("list",['model'=>$model]);
    }

    public function actionModify() {
        $id = \Yii::$app->request->get("id",0);
        $params = \Yii::$app->request->post("form");
        $model = Article::modelById($id);
        $params['cate_id'] = isset($params['cate_id'])&&is_array($params['cate_id'])?implode(",",array_values($params['cate_id'])):'';
        $model->setAttributes($params);
        if (!$model->save()) {
            return ResultFormat::error($model->getErrorsToString());
        }
        return ResultFormat::success("操作成功");
    }

    public function actionEdit() {
        $id = \Yii::$app->request->get("id",0);
        $model = Article::modelById($id);
        $allTags = TagService::strAlltagsByInput();
        return $this->render("edit",[
            'model'=>$model,
            'allTags' => $allTags
        ]);
    }

    /**
     * 审核文章
     */
    public function actionAuth($id) {
        $model = Article::modelById($id);
        $tags = $model->getArticleTags();
        return $this->render("auth",[
            "model" => $model,
            'tag_str' => json_encode($tags)
        ]);
    }

    /*
     * 审核文章提交
     */
    public function actionAudit($id) {
        $post = \Yii::$app->request->post("form");
        return ArticleService::auditArticle($id,$post);
    }

    public function actionNew() {
        $content = \Yii::$app->request->post("content");
        return \GuzzleHttp\json_encode(['content'=>ArticleService::addTagUrl($content)]);
    }

}
